package com.wxl.common.work

import androidx.appcompat.app.AppCompatActivity
import com.wxl.common.life.ViewModelQuick
import com.wxl.common.util.Loog

class Work {

    companion object {

        private val works = HashMap<String,Works>()

        fun addWork(key:String,works:Works){
            this.works[key] = works
        }

        /**
         * 执行下一个任务
         */
        fun doNext(key:String,lifeOwner: AppCompatActivity,vararg args:Any){
            if(works.containsKey(key)){
                if(works[key] != null){
                    works[key]!!.doWork(lifeOwner, *args)
                }
            }
        }

        /**
         * 停止任务
         */
        fun stop(key:String){
            if(works.containsKey(key)){
                if(works[key] != null){
                    works[key]!!.stopWork = true
                }
            }
        }

        /**
         * 恢复任务
         */
        fun restore(key:String){
            if(works.containsKey(key)){
                if(works[key] != null){
                    works[key]!!.stopWork = false
                }
            }
        }

        /**
         * 跳到哪个任务执行
         */
        fun <W:AbsWork> toDoWork(work: Class<W>,key:String,lifeOwner: AppCompatActivity,vararg args:Any){
            if(works.containsKey(key)){
                if(works[key] != null){
                    works[key]!!.findWorkToDo(work, lifeOwner, *args)
                }
            }
        }

        /**
         * 强制执行一个任务
         */
        fun <W:AbsWork> exeWork(work: Class<W>,key:String,lifeOwner: AppCompatActivity,vararg args:Any){
            if(works.containsKey(key)){
                if(works[key] != null){
                    val b = works[key]!!.findWorkToDo(work, lifeOwner, *args)
                    if(!b){
                        ViewModelQuick.observer(lifeOwner,work).mOnWorkCallback?.onWorkStart(*args)
                        ViewModelQuick.observer(lifeOwner,work).doWork(*args)
                    }
                }
            }
        }

        /**
         * 重新开始执行任务
         */
        fun reStart(key:String,lifeOwner: AppCompatActivity,vararg args:Any){
            if(works.containsKey(key)){
                if(works[key] != null){
                    works[key]!!.reStartWork(lifeOwner, *args)
                }
            }
        }

        /**
         * 重新执行本任务
         */
        fun retry(key:String,lifeOwner: AppCompatActivity,vararg args:Any){
            if(works.containsKey(key)){
                if(works[key] != null){
                    works[key]!!.retryWork(lifeOwner, *args)
                }
            }
        }

        /**
         * 释放
         */
        fun release(key: String){
            if(works.containsKey(key)){
                works.remove(key)
            }
        }
    }
}